package com.zlgs.cqyf.vote;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;


/**
 * Servlet implementation class FileUploadServlet
 */
 
public class FileUploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public FileUploadServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		JSONObject retObj = new JSONObject();
    	PrintWriter printWriter = response.getWriter();
    	try {
			request.setCharacterEncoding("UTF-8");
			response.setCharacterEncoding("UTF-8");
			response.setContentType("application/json; charset=utf-8");
			String retBasePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+ request.getContextPath();
			String basePath =  this.getServletContext().getContextPath();
			String basePath2 =  request.getContextPath();
			String basePath3 =  request.getRealPath("/");;
			retObj.put("basePath", basePath);
			retObj.put("basePath2", basePath2);
			retObj.put("basePath3", basePath3);
			retObj.put("retBasePath", retBasePath);
    	} catch (Exception e) {
			e.printStackTrace();
			retObj.put("code", "200");
			retObj.put("msg",e.getMessage());
		}finally{
			printWriter.append(retObj.toJSONString());
		}
	}
	 
	    
	    /**
	     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	     */
	    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	    	String basePath =  request.getRealPath("/");
	    	String tempPath = "portals"+File.separator+"vote"+File.separator+"pic"+File.separator;
	    	JSONObject retObj = new JSONObject();
	    	PrintWriter printWriter = response.getWriter();
	    	try {
				response.setCharacterEncoding("UTF-8");
				response.setContentType("application/json; charset=utf-8");
				byte[] body = readBody(request);
				String textBody = new String(body, "ISO-8859-1");
				String filename = getFilename(textBody);
				Position p = getFilePosition(request, textBody);
				writeTo(retObj,filename,basePath,tempPath, body, p);
				String retfilename = tempPath+filename;
				retObj.put("code", "200");
				retObj.put("data",retfilename);
			} catch (Exception e) {
				e.printStackTrace();
				retObj.put("code", "200");
				retObj.put("msg",e.getMessage());
			}finally{
				printWriter.append(retObj.toJSONString());
			}
	    }
	    
	    
	    private byte[] readBody(HttpServletRequest request)
	            throws IOException{
	        int formDataLength = request.getContentLength();
	        DataInputStream dataStream = new DataInputStream(request.getInputStream());
	        byte body[] = new byte[formDataLength];
	        int totalBytes = 0;
	        while (totalBytes < formDataLength) {
	        int bytes = dataStream.read(body, totalBytes, formDataLength);
	        totalBytes += bytes;
	        }
	        return body;
	    }
	    
	    private Position getFilePosition(HttpServletRequest request, String textBody) throws IOException {
	    
		    String contentType = request.getContentType();
		    String boundaryText = contentType.substring(
		            contentType.lastIndexOf("=") + 1, contentType.length());
		    int pos = textBody.indexOf("filename=\"");
		    pos = textBody.indexOf("\n", pos) + 1;
		    pos = textBody.indexOf("\n", pos) + 1;
		    pos = textBody.indexOf("\n", pos) + 1;
		    int boundaryLoc = textBody.indexOf(boundaryText, pos) -4;
		    int begin = ((textBody.substring(0, 
		            pos)).getBytes("ISO-8859-1")).length;
		    int end = ((textBody.substring(0, 
		            boundaryLoc)).getBytes("ISO-8859-1")).length;
		    
		    return new Position(begin, end);
	    }
	    
	    private String getFilename(String reqBody) {
	    	String newFileName = UUID.randomUUID().toString().replace("-","");
	        String filename = reqBody.substring(reqBody.indexOf("filename=\"") + 10);
	        filename = filename.substring(0, filename.indexOf("\n"));
	        filename = filename.substring(  filename.lastIndexOf("\\") + 1, filename.indexOf("\""));
	        newFileName  =newFileName+filename.substring(filename.lastIndexOf("."), filename.length());
	        return newFileName;
	    }
	    
	    private  void writeTo(JSONObject retObj,String filename,String basePath,String tempPath, byte[] body, Position p)  throws FileNotFoundException, IOException {
	    	String  filePath = basePath+File.separator+tempPath;
	    	File file = new File(filePath);
			//判断上传文件的保存目录是否存在
			if (!file.exists() && !file.isDirectory()) {
				//创建目录
				file.mkdir();
			}
			String fileAllPath = filePath+File.separator+filename;
	    	FileOutputStream fileOutputStream =  new FileOutputStream(fileAllPath,true);
	        fileOutputStream.write(body, p.begin, (p.end - p.begin));
	        fileOutputStream.flush();
	        fileOutputStream.close();
	    }

}
